<template>
  <el-card>
    <div class="toolbar">
      <el-input v-model="keyword" placeholder="搜索软件名称" style="width: 240px" clearable @keyup.enter="loadList" />
      <el-button type="primary" @click="loadList">搜索</el-button>
      <el-button type="success" @click="goToEdit(0)">添加软件</el-button>
    </div>

    <el-table :data="list" style="width: 100%; margin-top: 20px">
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="version" label="版本" width="100" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="license" label="协议" width="100" />
      <el-table-column prop="update_time" label="更新时间" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="goToEdit(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      :page-size="pageSize"
      layout="prev, pager, next"
      :total="total"
      @current-change="loadList"
      class="pagination"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getSoftwareList } from '@/api'
import { deleteSoftware } from '@/api/admin'
import { useRouter } from 'vue-router'
import type { SoftwareListItem } from '@/types/api'

const router = useRouter()

const keyword = ref('')
const list = ref<SoftwareListItem[]>([])
const page = ref(1)
const pageSize = 10
const total = ref(0)

async function loadList() {
  const res = await getSoftwareList({ keyword: keyword.value, page: page.value, page_size: pageSize })
  list.value = res.items
  total.value = res.total
}

function goToEdit(id: number) {
  router.push({ name: 'AdminSoftwareEdit', params: { id: id.toString() } })
}

async function handleDelete(id: number) {
  if (confirm('确认删除此软件？')) {
    await deleteSoftware(id)
    loadList()
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
